package com.wang.service;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.wang.dao.mapper.ArticleTagMapper;
import com.wang.dao.mapper.TagMapper;
import com.wang.pojo.ArticleTag;
import com.wang.pojo.Tag;
import com.wang.vo.Result;
import com.wang.vo.TagVo;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

@Service
public class TagServiceImpl implements TagService {

    @Autowired
    private TagMapper tagMapper;

    @Autowired
    private ArticleTagMapper articleTagMapper;

    @Autowired
    private ArticleService articleService;

    @Override
    public List<TagVo> findTagsByArticleId(Long id) {
        List<Tag> tags = tagMapper.findTagsByArticleId(id);
        return copyList(tags);
    }

    @Override
    public Result findHotsTagId(int limit) {

        List<Long> hotsTagId = tagMapper.findHotsTagId(limit);
        if(CollectionUtils.isEmpty(hotsTagId)) {
            return Result.success(Collections.emptyList());
        }
        List<Tag> tagList = tagMapper.findTagsByTagsId(hotsTagId);
        System.out.println(tagList);
        return Result.success(copyList(tagList));
    }

    @Override
    public Result findAll() {
        List<Tag> tags = tagMapper.selectList(new LambdaQueryWrapper<>());
        return Result.success(copyList(tags));
    }

    @Override
    public Result listArticleByTagIdPage(int offset, int size, Long tagId) {
        Page<ArticleTag> articleTagPage = new Page<>(offset, size);
        LambdaQueryWrapper<ArticleTag> tagLambdaQueryWrapper = new LambdaQueryWrapper<>();
        tagLambdaQueryWrapper.eq(ArticleTag::getTagId, tagId);
        Page<ArticleTag> tagPage = articleTagMapper.selectPage(articleTagPage, tagLambdaQueryWrapper);
        List<ArticleTag> tagList = tagPage.getRecords();
        long total = tagPage.getTotal();
        List<Long> list = new ArrayList<>();
        for (ArticleTag articleTag : tagList) {
            list.add(articleTag.getArticleId());
        }
        return articleService.listArticleByTagIdPage(list, tagId, total);
    }

    private List<TagVo> copyList(List<Tag> tagList) {
        List<TagVo> tagVoList = new ArrayList<>();
        for (Tag tag : tagList) {
            tagVoList.add(copy(tag));
        }
        return tagVoList;
    }

    private TagVo copy(Tag tag) {
        TagVo tagVo = new TagVo();
        BeanUtils.copyProperties(tag, tagVo);
        return tagVo;
    }
}
